package br.com.ufpr.sgp.components;

import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AbstractAutoCompleteRenderer;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.request.Response;
import org.apache.wicket.util.string.Strings;

import br.com.sebrae.pr.sgp.util.IAutocompletable;

public class CustomAbstractAutoCompleteRenderer<T> extends AbstractAutoCompleteRenderer<T> {
    private static final long serialVersionUID = 651757307340389995L;

    private final IAutocompletable<T> autocompletable;
    private final HiddenField<String> idField;

    public CustomAbstractAutoCompleteRenderer(final IAutocompletable<T> autocompletable, final HiddenField<String> idField) {
        this.autocompletable = autocompletable;
        this.idField = idField;
    }

    @Override
    public void render(final T object, final Response response, final String criteria) {
        String textValue = getTextValue(object);
        if (textValue == null) {
            throw new IllegalStateException("A call to textValue(Object) returned an illegal value: null for object: " + object.toString());
        }
        if (removeHtmlTags()) {
            textValue = Strings.escapeMarkup(textValue).toString();
        }
        response.write("<li textvalue=\"" + textValue + "\"");
        final CharSequence handler = getOnSelectJavaScriptExpression(object);
        if (handler != null) {
            response.write(" onselect=\"" + handler + '"');
        }
        response.write(">");
        renderChoice(object, response, criteria);
        response.write("</li>");
    }

    @Override
    protected String getTextValue(final T obj) {
        return autocompletable.getText(obj);
    }

    @Override
    protected void renderChoice(final T obj, final Response response, final String criteria) {
        response.write(autocompletable.getChoice(obj, criteria));
    }

    @Override
    protected CharSequence getOnSelectJavaScriptExpression(T item) {
        return "document.getElementById('" + idField.getMarkupId() + "').value='" + autocompletable.getChoiceId(item) + "'; $('#"
                + idField.getMarkupId() + "').change(); input";
    }

    public boolean removeHtmlTags() {
        return true;
    }
}
